UNIX

EXPORT TABELLE ORACLE TO ALTRO SCHEMA
COME SI FA AD EXPORT DELLE TABELLE DA UNO SCHEMA ORACLE?
####################################################################################################
Per l'HELP su UNIX:
exp help=y

You can let Export prompt you for parameters by entering the EXP command followed by your username/password:
Example: EXP SCOTT/TIGER
Format: EXP KEYWORD=value or KEYWORD=(value1,value2,...,valueN)
Example: EXP SCOTT/TIGER GRANTS=Y TABLES=(EMP,DEPT,MGR)
or TABLES=(T1:P1,T1:P2), if T1 is partitioned table
USERID must be the first parameter on the command line.
-----------------------------------
KEYWORD DESCRIPTION (DEFAULT)
-----------------------------------
USERID username/password
BUFFER size of data buffer
FILE output files (EXPDAT.DMP)
COMPRESS import into one extent (Y)
GRANTS export grants (Y)
INDEXES export indexes (Y)
ROWS export data rows (Y)
CONSTRAINTS export constraints (Y)
LOG log file of screen output
DIRECT direct path (N)
FULL export entire file (N)
OWNER list of owner usernames
TABLES list of table names
RECORDLENGTH length of IO record
INCTYPE incremental export type
RECORD track incr. export (Y)
PARFILE parameter filename
CONSISTENT cross-table consistency
STATISTICS analyze objects (ESTIMATE)
TRIGGERS export triggers (Y)
FEEDBACK display progress every x rows (0)
FILESIZE maximum size of each dump file
QUERY select clause used to export a subset of a table
VOLSIZE number of bytes to write to each tape volume

The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE export transportable tablespace metadata (N)
TABLESPACES list of tablespaces to transport

Export terminated successfully without warnings.
####################################################################################################

Se si tratta di esportare tante tabelle da Oracle conviene fare un file excel di questo tipo:XLS
In modo tale che si ha l'elenco del codice da lanciare in un sol colpo, c'è anche semplicità a cambiare i parametri

Creare un file con il codice: EXP_TABELLE.SRC

echo "[ `date '+ %d/%m/%y %H:%M:%S'` ]" (da usare se si lancia lo script in DOS altrimenti togliere)

exp TEST6/TEST6 FILE=exp_COMUNI.dmp TABLES=COMUNI grants=n indexes=n LOG=exp_COMUNI.log direct=y triggers=n feedback=100000

SPIEGAZIONE PARAMETRI:
TEST6/TEST6: utente/password del DB da cui si esporta
FILE=exp_COMUNI.dmp: Il nome del file che verrà creato dalla esportazione
grants=n
indexes=n
LOG=exp_COMUNI.log: Nome del file di LOG
direct=y: Modalità di esportazione più veloce. È incompatibile con un eventuale query
Per usare la direct bisogna eseguire questo codice per il tipo di caratteri nel caso di problemi:
NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P15
export NLS_LANG

OPPURE al contrario
NLS_LANG=AMERICAN_AMERICA.WE8DEC
export NLS_LANG

triggers=n
feedback=100000: Ogni 100000 record inseriti mette un puntino in più sul log.
query=\"where COM_UTE in \(\'IM\',\'IF\'\)\": Permette di fare una query. Attenzione che rallenta molto l'esportazione oltre al fatto che non permette di usare la direct.

Mettere exp_tabelle.src su Unix con WINSCP entrando come DB dell'utente da esportare.
Usare una cartella base dove mettere tutto
Dare i diritti allo script (da Putty, in Winscp fare CTRL+P):
chmod 777 exp_tabelle.src

eseguire lo script scrivendo:

./exp_tabelle.src
oppure lanciandolo in background (davanti nohup e alla fine &) che è meglio
nohup ./exp_tabelle.src &
si ottengono così i file:
exp_COMUNI.dmp
exp_COMUNI.log da leggere per verificare eventuali errori


COME SI FA AD IMPORTARE DELLE TABELLE DA UNO SCHEMA DB1 a DB2 ORACLE?
FASE ALLINEAMENTO
Prima di importare dati bisogna allineare le tabelle del DB2 a quelle del DB1.
Con toad 8.5 c'è una funzione TOOLS >> SINGLE OBJECT COMPARISION
Inserire le due tabelle da confrontare e selezionare RESULTS AS SYNC SCRIPT in modo tale che si ha subito il codice sql per il riallineamento. I disallineamenti in cui si diminuisce la dimensione di un campo non si devono considerare.

VELOCIZZAZIONE
Per velocizzare l'importazione si consiglia per tabelle oltre 500 Mb di dimensione di togliere gli index (sopo averli salvati) per poi ricrearli dopo l'importazione.

Per tante tabelle usare un file excel come sopra

CODICE IMPORTAZIONE:
imp ISUINT/ISUINT FILE=exp_COMUNI.dmp FROMUSER=TEST4 TOUSER=ISUINT LOG=imp_COMUNI.log ignore=y feedback=100000

Passi successici come sopra.


IN CASO DI ERRORI
Prima di reimportare fare il DELETE dei dati caricati parzialmente.
Usare questo script:

SE IN FASE DI IMP SU LOG c'è:
ORA-00001: unique constraint (ISUINT.I1_COMUNI) violated
Può essere che:
1) hanno indici univoci diversi. In questo caso si potrebbe cancellare l'indice e ricreare quello nuovo in base alla tabella di partenza.
2) tenta di ricaricare dati già presenti. Per questo bisogna verificare prima se spianare le tabelle prima o i dati vecchi.
3) Verificare se record scartati non servono
4) verificare impostazione di un campo flag_caricamento (ex: metterlo a 1 a quelli già caricati)


COME LANCIARE UN SELECT (o DELETE o altro) DA UNIX?
Aprire Putty
mettere nome DB per autenticazione
scrivere:
sqlplus user/password
si ha sql>
Scrivere la select finendo con un punto e virgola ";", dare INVIO e ok.
Su TOAD in questo caso se si va sullo SESSION BROWSER e si va su LONG OPS si vede l'avanzamento della select.

######################################################################################àà
Per l'HELP su UNIX:
imp help=y
You can let Import prompt you for parameters by entering the IMP command followed by your username/password:
Example: IMP SCOTT/TIGER
Format: IMP KEYWORD=value or KEYWORD=(value1,value2,...,valueN)
Example: IMP SCOTT/TIGER IGNORE=Y TABLES=(EMP,DEPT) FULL=N
or TABLES=(T1:P1,T1:P2), if T1 is partitioned table
USERID must be the first parameter on the command line.
--------------------------------
Keyword Description (Default)
--------------------------------
USERID username/password
BUFFER size of data buffer
FILE input files (EXPDAT.DMP)
SHOW just list file contents (N)
IGNORE ignore create errors (N)
GRANTS import grants (Y)
INDEXES import indexes (Y)
ROWS import data rows (Y)
LOG log file of screen output
FULL import entire file (N)
FROMUSER list of owner usernames
TOUSER list of usernames
TABLES list of table names
RECORDLENGTH length of IO record
INCTYPE incremental import type
COMMIT commit array insert (N)
PARFILE parameter filename
CONSTRAINTS import constraints (Y)
DESTROY overwrite tablespace data file (N)
INDEXFILE write table/index info to specified file
SKIP_UNUSABLE_INDEXES skip maintenance of unusable indexes (N)
ANALYZE execute ANALYZE statements in dump file (Y)
FEEDBACK display progress every x rows(0)
TOID_NOVALIDATE skip validation of specified type ids
FILESIZE maximum size of each dump file
RECALCULATE_STATISTICS recalculate statistics (N)
VOLSIZE number of bytes in file on each volume of a file on tape

The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set

Import terminated successfully without warnings.
###############################################################################################
COME SI FA AD IMPORTARE DELLE TABELLE DA UNO SCHEMA ORACLE?
DA PROMPT DOS STESSA CARTELLA CON exp_PONZIO.dmp(anche da UNIX)
BATCH
echo " # Inizio IMPORT di PONZIO su istanza PROVA4 [ `date '+ %d/%m/%y %H:%M:%S'` ]"
imp PROVA4/PROVA4 FILE=exp_PONZIO.dmp FROMUSER=UTE TOUSER=PROVA4 LOG=IMP_PONZIO.LOG IGNORE=Y
echo " # FINE FATTUR [ `date '+ %d/%m/%y %H:%M:%S'` ]"

############
Se uno SCRIPT A RICHIAMA UNO SCRIPT B con una EXIT alla Fine, non TORNA SU A

exp USER/PASS@DB.world PARFILE=exp.txt
imp system/pass@RD.world FROMUSER=user1 TOUSER=user2 FILE=exp.dmp LOG=imp.LOG

imp system/pass fromuser=user2 touser=user1 file=/oracle/.../exp_file.dmp feedback=10000 commit=y ignore=y log=/oracle/.../imp_file.log

NB. SOTTO UNIX non ci vuole @RD.world!!


########################### PASSI CARICAMENTO DATI
ROOT:
bwq:/home/usrRD>#
Mettere nella stessa cartella UNIX i seguenti file (con winSCP3):
nomefile.txt >> file Ascii con i dati
namecontrolfile.ctl >>
caricafile.bat >> file con istruzione di caricamento

dare i diritti di esecuzione: chmod 777 file.bat
Putty >> usr/pass


CHIAMATA IN BACKGROUND
nohup ./carica.bat dir/nomefile h_letture _g01 &

nohup ./carica.bat nomefile1 h_contratti1 _a01 &

CASI DI ERRORI IN CARICAMENTO
LEGGERE BENE IL LOG o IL NOHUP.OUT
0) Nella corrispondenza campi con i ctl le costanti non vengono contate
1) Se non può inserire un NULL in un campo disabilitare il Costraints di quel campo (con toad, premere l'icona lampadina bianca)
2) Se dice che il valore non entra nel campo può darsi che bisogna trasformarlo in ASCII UNIX
3) Errore slqloader 905 >> non dipende dai dati >> DA VERIFICARE!! >> molto probabilmente non ha caricato molti record
4) Attenti al separatore. A volte c'è il PIPE |
5) Con la clausola WHEN vengono direttamente eliminati determinati record. E quindi non è un errore ma è voluto!
6) Record 50681: Rejected - Error on table RECBAN.
ORA-00001: unique constraint (TB.I1_REC) violated >>
7) Attenzione della virgola al posto del punto >> mettere: "replace(:BON_VAL1,',','.')"


1) I file dati devono essere ASCII UNIX (in alcuni casi non c'è bisogno, però è fondamentale nei casi in cui l'ultimo dato ha un numero di caratteri uguali al num max del campo, infatti in tal caso sotto unix, prende il formato PC e considera il Carriage Line (CL) e il Line Feed (LF) come un ulteriore carattere e quindi va fuori dimensione)
2)FILE BAT di caricamento: carica3u.bat (u sta per unix) Deve essere in ASCII UNIX (edit plus >> document >> file format >> Unix)

#export NLS_NUMERIC_CHARACTERS=., #(questa istruzione non va bene con il nohup e quindi bisogna scrivere come segue)
NLS_NUMERIC_CHARACTERS=.,
export NLS_NUMERIC_CHARACTERS
sqlldr ISURDTEST/ISURDTEST DATA=$1.txt CONTROL=CTL/$2.ctl log=LOG_PASSAGGIO/$2$3.log bad=BAD_PASSAGGIO/$2$3.bad errors=100000

3) UN FILE .BAT CON IL LANCIO A TUTTI GLI SCRIPT, AD ESEMPIO:

echo './carica.bat nomefile h_note _01' >>>(da mettere in modo tale da leggere bene il nohup.out)
./carica3u.bat nomefile h_note _01
echo './carica3u.bat nomefile2 h_let _a01'
./carica3u.bat nomefile2 h_let _a01
exit >> per uscire dal nohup

funziona se viene chiamato come >> ./nomescript.bat
ma se lo si chiama con >> nohup ./nomefile.bat &
bisogna riscrivere la
export NLS_NUMERIC_CHARACTERS=.,
in 2 righe separate:
NLS_NUMERIC_CHARACTERS=.,
export NLS_NUMERIC_CHARACTERS
INOLTRE lo script chiamante deve essere in formato ASCII UNIX!!!







NOTE
Tutti i file creati in ambiente Windows sono in formato DOS che hanno
la caratteristica di avere l'elemento di ritorno a capo come 2 "caratteri" ascii:

CR Carriage Returns (ritorno a capo) - cod.Ascii:32
+
LF Line Feed (avanzo di una riga) - cod.Ascii:10

mentre sotto UNIX esiste solo il LF (^M).

PROBLEMA:
In operazioni di caricamento dei dati da file ascii con il sqlldr ci sono problemi nel caricamento dell'ultimo campo che porta a volta allo scarto totale dei dati.

SOLUZIONE1:
Con l'ftp portare il file Ascii in locale (se sono pesanti usare: zip nome.zip nome.txt e unzip nome.zip) e aprire con:
Ultraedit >> File >> Conversions >> Dos to UNIX
Ediplus >> Document >> File Format (CR/LF) >> Unix
Per l'ftp in generale usare il protocollo Binary che non fa mai variare il formato.

SOLUZIONE2: (più veloce e soprattutto utile quando i file ascii sono molto pesanti)
sotto UNIXeseguire:
dos2unix nomefiledos.txt nomefileunix.txt
oppure se si vuole trasformare direttamente lo stesso file
dos2unix nomefile.txt nomefile.txt
############################################################################








#### AUMENTARE DIM TABLESPACES #####################################################
jolly:/oracle/test2># sqlplus system/password
SQL> select file_name from dba_data_files where tablespace_name=STRUTTURA_IDX;
SQL> alter database datafile '/oracle/RD/oradata3/struttura_regionale_idx_01.dbf' resize 500M;






###################################################################################

########### PRIORITà ###############################
nice -priorità(20 a -20) (lancio del processo)
renice -priorità (20 - 20) PID di UNIX - SPID di Toad



############################################################################
Se si deve lanciare uno script in background in unix e si vuole ottenere un file di spool con nome diverso dal solito nohup.out (che potrebbe contenere anche lo spool di script lanciati da altri) si può fare così:
nohup ./nomescript.bat > nohup_nomescript.out &
############################################################################


############################################################################
esc+l >> esc+x Cancella
############################################################################

################# DIMENSIONI HARD DISK ###################################
df -k
############################################################################


################# CPU USAGE ###################################
prstat : tutti i processi >> Utilizzo della CPU
prstat 2 200 : tutti i processi con aggiornamento ogni 2 secondi per 200 volte
prstat -p numero.id : trova l'uso della cpu del processo
df : Occupazione su disco
iostat 2 1000 > cpu_usage.log : Salva nel file l'uso della CPU (ogni 2 secondi per 100 volte)

NB: PID = SPID del Session Browser TOAD (in corrispondenza del processo).
Mentre il PROCESS del TOAD corrisponde al numero del processo che si ottiene con:
ps -efa|grep sqlplus : Trova i processi con la parola "sqlplus"
KILLARE PROCESSO: kill -9 2931 : Numero subito dopo il nome = Process sul TOAD e poi KILL SPID del TOAD (se è stato chiamato da un nohup in sh multiplo cercare anche quel processo in genere di un numero più piccolo al process)
In genere bisogna anche killare sia il processo padre che il figlio altrimenti rimane loccato. Questo capita quando si compila e la funzione è in esecuzione.
####################################
ps -efa|grep exp*

kill -9 (num di fianco processo)

Creare uno script sql così:

spool killaprocessadasql.out
set pagesize 66
col c1 for a9
col c1 heading "OS User"
col c2 for a9
col c2 heading "Oracle User"
col b1 for a9
col b1 heading "Unix PID"
col b2 for 9999 justify left
col b2 heading "SID"
col b3 for 99999 justify left
col b3 heading "SERIAL#"
col sql_text for a35
break on b1 nodup on c1 nodup on c2 nodup on b2 nodup on b3 skip 3
select c.spid b1, b.osuser c1, b.username c2, b.sid b2, b.serial# b3,
a.sql_text
from v$sqltext a, v$session b, v$process c
where a.address = b.sql_address
-- and b.status = 'ACTIVE' /* YOU CAN CHOOSE THIS OPTION ONLY TO SEE
-- ACTVE TRANSACTION ON THAT MOMENT */
and b.paddr = c.addr
and a.hash_value = b.sql_hash_value
order by c.spid,a.hash_value,a.piece
/


da sqlplus in unix
lanciare script: SQL> @nomescript.sql

alter system kill session 'SID,SERIAL'
####################################
ctrl+c per uscire

################## KILL ########################################
UNIX
Killing sessions in the UNIX environment ps -ef | grep ora to find Oracle processes. Be sure to get the process id of the session you are trying to kill.

kill -1
or
kill -9
kill -9 5745
All in one kill ps -ef | grep pmon_$ORACLE_SID | awk '{print $2}' | xargs kill -9

WINDOWS
Killing sessions in the Windows environment with ORAKILL. Note: "orabase" below is the instance name available from v_$instance

orakill
SELECT instance_name
FROM v$instance;

col program format a30

SELECT spid, osuser, s.program, schemaname
FROM v$process p, v$session s
WHERE p.addr = s.paddr;

c:\oracle\product\ora102\bin> orakill orabase spid

ALL
Killing sessions from inside the database To kill sessions within the database requires the ALTER SYSTEM privilege and the sid and serial# of the session to be killed

GRANT alter system TO ;

SELECT sid, serial# , username, schemaname, osuser
FROM v$session
WHERE username = ;

ALTER SYSTEM KILL SESSION ',';
conn / as sysdba

GRANT alter system TO aqadmin;

conn aqadmin/aqadmin

SELECT sid, serial# , username, schemaname, osuser
FROM v$session
WHERE username = 'AQUSER';

SQL> ALTER SYSTEM KILL SESSION '9,177' IMMEDIATE;

KILL ALL SESSIONS
Kill All Instance Sessions conn / as sysdba

set heading off
set termout off
set verify off
set echo off
set feedback off

ALTER SYSTEM enable restricted session;

ALTER SYSTEM checkpoint global;

spool kill_all.sql

SELECT 'execute kill_session('|| chr(39) || sid || chr(39) || ',' || chr(39) || serial# || chr(39) || ');'
FROM v_$session
WHERE (username IS NOT NULL OR username <> 'SYS');

spool off

@kill_all

SESSION KILL DEMO PROCEDURE
An infinite loop for testing CREATE OR REPLACE PROCEDURE infinite_loop IS

BEGIN
LOOP
NULL;
END LOOP;
END infinite_loop;
/

SQL> exec infinite_loop
############################################################################
CONTROLLARE LA DISPONIBILITÀ DELLA CPU USARE:
iostat 2 1000 (cioè legge ogni 2 secondi per 1000 volte)
Esaminare le ultime 4 colonne:
us: % cpu usata dagli utenti
sy: % cpu usata dal sistema
wt: % cpu in stato di wait, quindi disponibile
id: % cpu in idle quindi disponibile
############################################################################


############ OPERAZIONE PIANIFICATA - SCHEDULAZIONE ############
at -f nomebacth.sh -t 200412010100 (la data:aaaammgghhmm )
at -l >> vedi i job schedulati
at -r idbacth >> per eliminarlo
############################################################################


############################################################################
RIGA COMANDI ($)


ISTRUZIONI UTILI
vi nohup.out
:q! >> per uscire dal vi senza salvare
ZZ >> uscire e salvare da vi
ps -efa|grep imp >> tutti i processi con imp
tail -100 nohup.out >> gli ultimi 100
tail -f nohup.out
echo $ORACLE_SID >> vedi l'utente
ORACLE_SID=APP >> Cambi utenti

head -n10 nomefile.txt > nomefilecon10riche.txt >> crea un nuovo file con le prime n righe
split >> divide un file in più file


cat nohup.out
cd ../..
cd /sambau/TRANSITI_TEST/TR_NORMALIZZATORE
cd TR*
chmod 777 carica3u.bat
df -k
df -k /exprt_ISU/
exit
history
kill -9 8562
ls -la
ls -ls
ls -lt
man nohup
more nohup.out
nohup ./importazioni.sh &
ps -efa|grep imp
sqlplus DBTEST/DBTEST
touch pippo >> crea file
wc -c pippo

wc -l FileProva.txt: Numero di righe nel file FileProva.txt